package com.magic.zhixin.handler.DelayTask;

import com.magic.zhixin.entity.UserInfo;
import com.magic.zhixin.entity.UserQuestion;
import com.magic.zhixin.repository.UserInfoRepository;
import com.magic.zhixin.repository.UserQuestionRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

/***
 * 定时任务消费，
 * 应用举例，用户只用实现接口 DelayTaskConsumer，即可
 */
@Component
@Slf4j
public class DelayTaskConsumerService implements DelayTaskConsumer {
    @Autowired
    private UserQuestionRepository userQuestionRepository;
    @Autowired
    private UserInfoRepository userInfoRepository;

    @Override
    public void consume(DelayedTask delayedTask) throws Exception {
        log.info("时间到，执行任务,任务类型：{}任务BussinessId{}：，任务endTime时间：{}" ,delayedTask.getTaskType(),delayedTask.getBussinessId(),delayedTask.getExecuteTime());
        if(1 == delayedTask.getTaskType()){
            //过期退款
            String bussinessId = delayedTask.getBussinessId();
            UserQuestion userQuestion = userQuestionRepository.findByIdIs(Long.valueOf(bussinessId));
            if(userQuestion.getPrizeAmount() < userQuestion.getRewardAmount()){
                BigDecimal per = userQuestion.getTotalBonus().divide(new BigDecimal(userQuestion.getRewardAmount()), BigDecimal.ROUND_DOWN, 2);
                UserInfo userInfo = userInfoRepository.findByIdIs(userQuestion.getUserId());
                userInfo.setBalance(userInfo.getBalance().add(new BigDecimal(userQuestion.getRewardAmount() - userQuestion.getPrizeAmount()).multiply(per)));
                userInfoRepository.save(userInfo);

                userQuestion.setQuestionProgress(2);
                userQuestionRepository.save(userQuestion);
            }
        }
    }

//    @Transactional(rollbackFor = Exception.class)
//    public void miaoOrderSettlement(DelayedTask delayedTask) throws Exception {
//        String bussinessId = delayedTask.getBussinessId();
//        Optional<MiaoOrder> optional = miaoOrderRepository.findById(Long.parseLong(bussinessId));
//        if(!optional.isPresent()){
//            log.error("合约结算失败,ID{}不存在", bussinessId);
//            return;
//        }
//        log.info("合约结算开始，合约详情{}",optional.get());
//        MiaoOrder miaoOrder = optional.get();
//        if(miaoOrder.getMiaoOrderStatus().getType() != MiaoOrderStatus.COMMIT.getType()){
//            log.error("合约结算失败，ID{}已处理",bussinessId);
//            return;
//        }
//        Ticker ticker = tickerRepository.findTop1ByCoinNameOrderByIdDesc(miaoOrder.getCoinName());
//        BigDecimal subtract = ticker.getPrice().subtract(miaoOrder.getBeginPrice());
//        miaoOrder.setEndPrice(ticker.getPrice());
//        Optional<MiaoRule> rule = ruleRepository.findById(miaoOrder.getRuleId());
//
//        BigDecimal percent = null;
//        if(subtract.compareTo(BigDecimal.ZERO) == 1){
//            //涨
//            percent = rule.get().getRaisePercent();
//            if(miaoOrder.getMiaoType().getType() == MiaoType.RAISE.getType()){
//                miaoOrder.setMiaoOrderStatus(MiaoOrderStatus.WON);
//            } else {
//                miaoOrder.setMiaoOrderStatus(MiaoOrderStatus.LOST);
//            }
//        } else if(subtract.compareTo(BigDecimal.ZERO) == 0){
//            //平
//            percent = rule.get().getFlatPercent();
//            if(miaoOrder.getMiaoType().getType() == MiaoType.FLAT.getType()){
//                miaoOrder.setMiaoOrderStatus(MiaoOrderStatus.WON);
//            } else {
//                miaoOrder.setMiaoOrderStatus(MiaoOrderStatus.LOST);
//            }
//        } else {
//            //跌
//            percent = rule.get().getFallPercent();
//            if(miaoOrder.getMiaoType().getType() == MiaoType.FALL.getType()){
//                miaoOrder.setMiaoOrderStatus(MiaoOrderStatus.WON);
//            } else {
//                miaoOrder.setMiaoOrderStatus(MiaoOrderStatus.LOST);
//            }
//        }
//
//        if(miaoOrder.getMiaoOrderStatus().getType() == MiaoOrderStatus.WON.getType()){
//            BigDecimal lock = miaoOrder.getLockAmount();
//            BigDecimal wonAmount = miaoOrder.getCost().multiply(percent);
//            miaoOrder.setResult(miaoOrder.getCost().add(wonAmount).subtract(lock));
//        }
//        if(miaoOrder.getMiaoOrderStatus().getType() == MiaoOrderStatus.LOST.getType()){
//            miaoOrder.setResult(miaoOrder.getCost().multiply(new BigDecimal(-1)));
//        }
//        miaoOrder.setEndPrice(ticker.getPrice());
//        miaoOrderRepository.save(miaoOrder);
//
//        //根据结果转账给用户
//        Long fUserId = dictionaryRedisService.getDictionaryLong(DictionaryType.MIAO_PLATFORM_ACCOUNT);
//        UserWallet fUserWallet = walletServiceImpNew.getUserWallet(fUserId, miaoOrder.getCoinName());
//        UserWallet tUserWallet = walletServiceImpNew.getUserWallet(miaoOrder.getUserId(), miaoOrder.getCoinName());
//        if(miaoOrder.getMiaoOrderStatus().getType() == MiaoOrderStatus.WON.getType()){
//            walletServiceImpNew.transferCore(fUserWallet,null,tUserWallet,null,miaoOrder.getCoinName()
//                    ,miaoOrder.getResult(), TransferType.MIAO_PROFIT,miaoOrder.getId().toString());
//        }
//        log.info("------合约结算成功------");
//    }
//
//    /**
//     * 风控管理
//     */
//    public void riskManagement(String coinName) throws Exception {
//        //计算当前游戏结果
//        List<MiaoOrder> miaoOrder30s = miaoOrderRepository.findByResultAndTimesAndEndTimeBefore(BigDecimal.ZERO,30, new Date());
//        List<MiaoOrder> miaoOrder60s = miaoOrderRepository.findByResultAndTimesAndEndTimeBefore(BigDecimal.ZERO,60, new Date());
//        List<MiaoOrder> miaoOrder90s = miaoOrderRepository.findByResultAndTimesAndEndTimeBefore(BigDecimal.ZERO,90, new Date());
//
//        //30S
//        BigDecimal raiseCost30s = miaoOrderRepository.sumCostByMiaoTypeAndResultAndTimesAndEndTimeBefore30s(MiaoType.RAISE, BigDecimal.ZERO, 30, new Date());
//        BigDecimal fallCost30s = miaoOrderRepository.sumCostByMiaoTypeAndResultAndTimesAndEndTimeBefore30s(MiaoType.FALL, BigDecimal.ZERO, 30, new Date());
//        BigDecimal flatCost30s = miaoOrderRepository.sumCostByMiaoTypeAndResultAndTimesAndEndTimeBefore30s(MiaoType.FLAT, BigDecimal.ZERO, 30, new Date());
//        //60s
//        BigDecimal raiseCost60s = miaoOrderRepository.sumCostByMiaoTypeAndResultAndTimesAndEndTimeBefore30s(MiaoType.RAISE, BigDecimal.ZERO, 60, new Date());
//        BigDecimal fallCost60s = miaoOrderRepository.sumCostByMiaoTypeAndResultAndTimesAndEndTimeBefore30s(MiaoType.FALL, BigDecimal.ZERO, 60, new Date());
//        BigDecimal flatCost60s = miaoOrderRepository.sumCostByMiaoTypeAndResultAndTimesAndEndTimeBefore30s(MiaoType.FLAT, BigDecimal.ZERO, 60, new Date());
//        //90s
//        BigDecimal raiseCost90s = miaoOrderRepository.sumCostByMiaoTypeAndResultAndTimesAndEndTimeBefore30s(MiaoType.RAISE, BigDecimal.ZERO, 90, new Date());
//        BigDecimal fallCost90s = miaoOrderRepository.sumCostByMiaoTypeAndResultAndTimesAndEndTimeBefore30s(MiaoType.FALL, BigDecimal.ZERO, 90, new Date());
//        BigDecimal flatCost90s = miaoOrderRepository.sumCostByMiaoTypeAndResultAndTimesAndEndTimeBefore30s(MiaoType.FLAT, BigDecimal.ZERO, 90, new Date());
//        //当前价格
//        Ticker ticker = tickerRepository.findTop1ByCoinNameOrderByIdDesc(coinName);
//        //判断当前价格对于30s 60s 90s涨跌结果
//        MiaoOrder order30s = miaoOrder30s.get(0);
//        MiaoType miaoType30s = null;
//        BigDecimal wave30 = BigDecimal.ZERO;
//        if(order30s != null){
//           if(order30s.getBeginPrice().compareTo(ticker.getPrice()) == 1){
//               miaoType30s = MiaoType.FALL;
//           } else if(order30s.getBeginPrice().compareTo(ticker.getPrice()) == 0) {
//               miaoType30s = MiaoType.FLAT;
//           } else {
//               miaoType30s = MiaoType.RAISE;
//           }
//           //计算行情波动
//            wave30 = ticker.getPrice().subtract(order30s.getBeginPrice()).divide(order30s.getBeginPrice(),4,BigDecimal.ROUND_DOWN).abs();
//        }
//        MiaoOrder order60s = miaoOrder60s.get(0);
//        MiaoType miaoType60s = null;
//        BigDecimal wave60 = BigDecimal.ZERO;
//        if(order60s != null){
//           if(order60s.getBeginPrice().compareTo(ticker.getPrice()) == 1){
//               miaoType60s = MiaoType.FALL;
//           } else if(order60s.getBeginPrice().compareTo(ticker.getPrice()) == 0) {
//               miaoType60s = MiaoType.FLAT;
//           } else {
//               miaoType60s = MiaoType.RAISE;
//           }
//            wave60 = ticker.getPrice().subtract(order60s.getBeginPrice()).divide(order60s.getBeginPrice(),4,BigDecimal.ROUND_DOWN).abs();
//        }
//        MiaoOrder order90s = miaoOrder30s.get(0);
//        MiaoType miaoType90s = null;
//        BigDecimal wave90 = BigDecimal.ZERO;
//        if(order90s != null){
//           if(order90s.getBeginPrice().compareTo(ticker.getPrice()) == 1){
//               miaoType90s = MiaoType.FALL;
//           } else if(order90s.getBeginPrice().compareTo(ticker.getPrice()) == 0) {
//               miaoType90s = MiaoType.FLAT;
//           } else {
//               miaoType90s = MiaoType.RAISE;
//           }
//            wave90 = ticker.getPrice().subtract(order90s.getBeginPrice()).divide(order90s.getBeginPrice(),4,BigDecimal.ROUND_DOWN).abs();
//        }
//        //各时间规则
//        MiaoRule rule30s = commRedisService.getRuleByLength(30);
//        MiaoRule rule60s = commRedisService.getRuleByLength(60);
//        MiaoRule rule90s = commRedisService.getRuleByLength(90);
//        //30s平台盈利 玩家盈利
//        WinResult winResult30s = new WinResult(raiseCost30s, fallCost30s, flatCost30s, miaoType30s, rule30s, BigDecimal.ZERO, BigDecimal.ZERO).invoke();
//        BigDecimal playerWin30s = winResult30s.getPlayerWin();
//        BigDecimal platformWin30s = winResult30s.getPlatformWin();
//        //60s平台盈利 玩家盈利
//        WinResult winResult60s = new WinResult(raiseCost60s, fallCost60s, flatCost60s, miaoType60s, rule60s, BigDecimal.ZERO, BigDecimal.ZERO).invoke();
//        BigDecimal playerWin60s = winResult60s.getPlayerWin();
//        BigDecimal platformWin60s = winResult60s.getPlatformWin();
//        //90s平台盈利 玩家盈利
//        WinResult winResult90s = new WinResult(raiseCost90s, fallCost90s, flatCost90s, miaoType90s, rule90s, BigDecimal.ZERO, BigDecimal.ZERO).invoke();
//        BigDecimal playerWin90s = winResult90s.getPlayerWin();
//        BigDecimal platformWin90s = winResult90s.getPlatformWin();
//        //本次结算总结果
//        BigDecimal platformTotalWin = platformWin30s.add(platformWin60s).add(platformWin90s);
//        BigDecimal playerTotalWin = playerWin30s.add(playerWin60s).add(playerWin90s);
//        if(platformTotalWin.compareTo(playerTotalWin) == -1){
//            //平台亏损调整价格
//            if(wave30.compareTo(new BigDecimal(0.1)) < 0){
//                return;
//            }
//
//            if(wave60.compareTo(new BigDecimal(0.1)) < 0){
//
//            }
//            if(wave90.compareTo(new BigDecimal(0.1)) < 0){
//
//            }
//        }
//
//
//    }
//
//    private class WinResult {
//        private BigDecimal raiseCost60s;
//        private BigDecimal fallCost60s;
//        private BigDecimal flatCost60s;
//        private MiaoType miaoType60s;
//        private MiaoRule rule60s;
//        private BigDecimal platformWin;
//        private BigDecimal playerWin;
//
//        public WinResult(BigDecimal raiseCost60s, BigDecimal fallCost60s, BigDecimal flatCost60s, MiaoType miaoType60s, MiaoRule rule60s, BigDecimal platformWin, BigDecimal playerWin) {
//            this.raiseCost60s = raiseCost60s;
//            this.fallCost60s = fallCost60s;
//            this.flatCost60s = flatCost60s;
//            this.miaoType60s = miaoType60s;
//            this.rule60s = rule60s;
//            this.platformWin = platformWin;
//            this.playerWin = playerWin;
//        }
//
//        public BigDecimal getPlatformWin() {
//            return platformWin;
//        }
//
//        public BigDecimal getPlayerWin() {
//            return playerWin;
//        }
//
//        public WinResult invoke() {
//            if(miaoType60s.getType() == MiaoType.RAISE.getType()){
//                platformWin = playerWin.add(fallCost60s.add(flatCost60s));
//                playerWin =playerWin.add(raiseCost60s.multiply(rule60s.getRaisePercent()));
//            } else if(miaoType60s.getType() == MiaoType.FALL.getType()){
//                platformWin =platformWin.add(raiseCost60s.add(flatCost60s));
//                playerWin = playerWin.add(fallCost60s.multiply(rule60s.getFallPercent()));
//            } else {
//                platformWin =platformWin.add(raiseCost60s.add(fallCost60s));
//                playerWin =playerWin.add(flatCost60s.multiply(rule60s.getFlatPercent()));
//            }
//            return this;
//        }
//    }
}



